package com.aboverock.module.system.service.impl;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.aboverock.module.system.domain.Resource;
import com.aboverock.module.system.domain.Role;
import com.aboverock.module.system.domain.User;
import com.aboverock.module.system.mapper.RoleMapper;
import com.aboverock.module.system.service.RoleResourceService;
import com.aboverock.module.system.service.RoleService;
import com.aboverock.module.system.service.UserRoleService;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Rock Wang
 * @since 2018-04-10
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Autowired
    private RoleService roleService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleResourceService roleResourceService;

    @Override
    public List<Role> getRoles() {
        List<Role> roles = roleService.list(null);
        for (Role role : roles) {
            List<String> userIds = userRoleService.getUserIdsByRoleId(role.getId());
            role.setUserIds(userIds);
            List<String> resourceIds = roleResourceService.getResourceIdsByRoleId(role.getId());
            role.setResourceIds(resourceIds);
        }

        return roles;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(String roleId) throws SQLException {
        Map<String, Object> map = new HashMap<String, Object>(1);
        map.put("role_id", roleId);

        try {
            roleResourceService.removeByMap(map);
            userRoleService.removeByMap(map);
            removeById(roleId);
        } catch (Exception e) {
            throw new SQLException(e);
        }
    }

    @Override
    public List<User> getUsersByRoleId(String roleId) {
        return baseMapper.getUsersByRoleId(roleId);
    }

    @Override
    public List<Resource> getResourcesByRoleId(String roleId) {
        return baseMapper.getResourcesByRoleId(roleId);
    }

    @Override
    public boolean isDuplicatedCode(Role role) {
        QueryWrapper<Role> query = new QueryWrapper<Role>().eq("code", role.getCode());
        // 如果是更新时，排除自身code
        if (role.getId() != null) {
            query.ne("id", role.getId());
        }

        return (null == getOne(query)) ? false : true;
    }

    @Override
    public Role getByRoleCode(String code) {
        return getOne(new QueryWrapper<Role>().eq("code", code));
    }

}
